import React, { Component } from 'react'
import _ from 'underscore'

export default class FormGroup extends Component {
    keyPress(e) {
        const { onEnter, onKeyUp } = this.props;
        if(e.keyCode == 13) {
            onEnter && onEnter()
        }
        onKeyUp && onKeyUp()
    }
    mouseBlur(e) {
        const { onBlur } = this.props;

        onBlur && onBlur()
    }
    render() {
        const { options, data, error, callback } = this.props;
        const type = options.type;
        const inputWidth = options.input_width || 10;
        const description = options.description;

        return <div className={"form-group"+(error && error.length?' has-error':'')}>
            <label htmlFor={type=='image'? '': null} >
                <div className="col-sm-2 control-label">{options.title}</div>
                <div className={"col-sm-" + inputWidth}>
                    {(() => {
                        switch(type) {
                            case 'image':
                                return <label className="avatar" style={{backgroundImage: 'url('+data+')'}}>
                                    <input type='file' style={{visibility: 'hidden'}} onChange={callback} />
                                </label>
                            case 'textarea':
                                return <textarea className="form-control" placeholder={options.placeholder} value={data} onChange={callback} disabled={options.disabled} onKeyUp={(e) => this.keyPress(e)} onBlur={(e) => this.mouseBlur(e)} />
                            case 'checkbox':
                                return <div className="checkbox">
                                    {options.options.map((i, index) => <label key={index} style={{marginRight:10}}>
                                        <input type="checkbox" onChange={callback} checked={_.contains(data, index)} /> {i.name}
                                    </label>)}
                                </div>
                            case 'input':
                            default:
                                return <input type={options.password? "password": "text"} className="form-control" placeholder={options.placeholder} value={data} onChange={callback} disabled={options.disabled}  onKeyUp={(e) => this.keyPress(e)} onBlur={(e) => this.mouseBlur(e)} />
                        }
                    })()}
                    {error && error.length? <span className="help-block">
                        {typeof error != 'string'?error.map((i, index) => <span key={i.id}>{i.error}</span>): error}
                    </span>: description? <span className="help-block">
                        {description}
                    </span>: null}
                </div>
            </label>
        </div>
    }
}